package io.github.shenbinglife.springboot2.layui.common.model;

import java.util.HashMap;
import java.util.Map;

public class Result<T> {
    public static final long SUCCESS_CODE = 0L;
    public static final long FAILURE_CODE = 1L;

    private long code;
    private String msg;
    private T data;
    private boolean success;

    public Result() {
    }

    public Result(long code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.success = code == SUCCESS_CODE;
    }

    public static <T> Result<T> success() {
        return new Result<>(SUCCESS_CODE, null, null);
    }

    public static <T>  Result<T> success(T data) {
        return new Result<>(SUCCESS_CODE, null, data);
    }

    public static <T> Result<T> failure (String message) {
        return new Result<>(FAILURE_CODE, message, null);
    }

    public static Result<Void> failure(long code, String message) {
        return new Result<>(code, message, null);
    }

    public Map<String, Object> toMap () {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("data", data);
        return map;
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                ", success=" + success +
                '}';
    }
}
